package com.mall.search.service.impl;

import cn.hutool.cache.impl.FIFOCache;
import co.elastic.clients.elasticsearch._types.aggregations.AggregateBuilders;
import co.elastic.clients.elasticsearch._types.aggregations.StringTermsAggregate;
import com.alibaba.fastjson.JSON;
import com.mall.common.dto.SkuEsModel;
import com.mall.common.page.PageData;
import com.mall.common.utils.Result;
import com.mall.search.config.ESConfig;
import com.mall.search.constant.EsConstant;
import com.mall.search.feign.ProductFeignClient;
import com.mall.search.service.SearchService;
import com.mall.search.vo.AttrResponseVo;
import com.mall.search.vo.SearchParam;
import com.mall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 谢君臣
 * @Date: 2022/8/2-20:06
 * @version: 1.0
 * @function:
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private RestHighLevelClient levelClient;

    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult searchResult = null;
        Integer size = searchParam.getPageSize();
        size = size == null || size <= 0 ? EsConstant.PAGE_SIZE : size;
        Integer page = searchParam.getPageNum();
        page = page == null || page <= 0 ? 1 : page;
        // 配置请求条件
        SearchRequest searchRequest = buildSearchRequest(searchParam, size, page);
        try {
            SearchResponse response = levelClient.search(searchRequest, ESConfig.COMMON_OPTIONS);
            // 封装页面展示数据

            searchResult = buildSearchResult(response, searchParam, size, page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam, Integer size, Integer page) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 模糊查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(searchParam.getKeyword()))
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        if (searchParam.getCatalog3Id() != null)
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0)
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        if (searchParam.getHasStock() != null && searchParam.getHasStock() > 0)
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] prices = searchParam.getSkuPrice().split("_");
            if (prices.length > 1) {
                rangeQuery.gte(prices[0]).lte(prices[1]);
            } else {
                if (searchParam.getSkuPrice().startsWith("_"))
                    rangeQuery.gte(prices[0]);
                else if (searchParam.getSkuPrice().endsWith("_"))
                    rangeQuery.lte(prices[0]);
            }
            boolQuery.filter(rangeQuery);
        }
        // 嵌套属性
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            searchParam.getAttrs().forEach(attr -> {
                BoolQueryBuilder nested = QueryBuilders.boolQuery();
                String[] attr_vo = attr.split("_");
                String attrId = attr_vo[0];
                String[] attrValue = attr_vo[1].split(":");
                nested.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nested.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nested, ScoreMode.Max);
                boolQuery.filter(nestedQuery);
            });
        }

        sourceBuilder.query(boolQuery);
        // 排序
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String sort = searchParam.getSort();
            String[] sort_value = sort.split("_");
            SortOrder order = sort_value[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(sort_value[0], order);
        }
        // 分页
        sourceBuilder.from((searchParam.getPageNum() - 1) * size);
        sourceBuilder.size(size);
        // 高亮
        if (StringUtils.isNotEmpty(searchParam.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        // 聚合分析
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId");
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName"));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg"));
        sourceBuilder.aggregation(brand_agg);

        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(1);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName"));
        sourceBuilder.aggregation(catalog_agg);

        // 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param, Integer size, Integer page) {
        SearchResult result = new SearchResult();
        // 商品数据
        SearchHits hits = response.getHits();
        // 分页数据
        long total = hits.getTotalHits().value;
        result.setPage(page);
        result.setTotal(total);
        result.setTotalPage((int) total % size == 0 ? (int) total / size : (int) total / size + 1);
        if (hits.getHits() != null && hits.getHits().length > 0) {
            List<SkuEsModel> skuList = new ArrayList<>();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku = JSON.parseObject(sourceAsString, SkuEsModel.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.get("skuTitle") != null) {
                    sku.setSkuTitle(highlightFields.get("skuTitle").getFragments()[0].toString());
                }
                skuList.add(sku);
            }
            result.setProduct(skuList);
        }
        // 聚合信息
        Aggregations aggregations = response.getAggregations();
        // 分类的id
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String catelogId = bucket.getKey().toString();
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            catalogVo.setCatalogId(Long.parseLong(catelogId));
            catalogVo.setCatalogName(catalog_name_agg.getBuckets().get(0).getKeyAsString());
            catalogVos.add(catalogVo);
        }
        result.setCatalogVos(catalogVos);
        // 当前查询所涉及的属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());

            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            attrVo.setAttrName(attr_name_agg.getBuckets().get(0).getKeyAsString());

            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> values = attr_value_agg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValues(values);

            attrVos.add(attrVo);
        }
        result.setAttrVos(attrVos);
        // 当前查询所涉及的品牌
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String brandId = bucket.getKey().toString();
            brandVo.setBrandId(Long.parseLong(brandId));
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
            brandVos.add(brandVo);
        }
        result.setBrandVos(brandVos);

        //6、构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                Result r = productFeignClient.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    HashMap<String,String> data = (HashMap<String, String>) r.getData();
                    navVo.setNavName(data.get("attrName"));
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+", "%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://search.mall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }
        return result;

    }

}
